package com.zhonghan.recharge.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.wechat.api.AuthApi;
import com.zhonghan.common.wechat.api.MenuApi;
import com.zhonghan.common.wechat.api.MessageApi;
import com.zhonghan.common.wechat.bean.menu.Button;
import com.zhonghan.common.wechat.bean.menu.MenuButtons;
import com.zhonghan.common.wechat.bean.result.BaseResult;
import com.zhonghan.recharge.service.MessageService;
import com.zhonghan.recharge.service.WechatAccountService;
import com.zhonghan.recharge.service.WechatReplyService;
import com.zhonghan.recharge.task.TaskList;


/**
 * 微信控制层
 * @author zhangceven
 *
 */
@RequestMapping("/wechat")
@Controller
public class WechatController {
	
	Logger logger = Logger.getLogger(WechatController.class);
	
	@Value("${wechat.TOKEN}")
	private String TOKEN;
	
	@Value("${wechat.DOMAIN}")
	private String DOMAIN;
	
	@Value("${wechat.APPID}")
	private String APPID;
	
	@Value("${wechat.APPSECRET}")
	private String APPSECRET;
	
	@Autowired
	private WechatAccountService wechatAccountService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired 
	private WechatReplyService wechatReplyService;
	/**
	 * 通过get请求验证签名
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@RequestMapping(value="/get", method=RequestMethod.GET)
	@ResponseBody
	public String checkName(String signature, String timestamp, String nonce, String echostr) {
		logger.info("微信公众号--开始校验签名");
		logger.info("收到来自微信的 signature 字符串: " + signature);
		logger.info("收到来自微信的 timestamp 字符串: " + timestamp);
		logger.info("收到来自微信的 nonce 字符串:     " + nonce);
		logger.info("收到来自微信的 echostr 字符串:   " + echostr);

		/*
		 * 加密/校验流程 1. 将token、timestamp、nonce三个参数按照字典顺序排序 2. 将三个参数字符串拼接成一个字符串进行
		 * sha1 加密 3. 开发者获得加密后的字符串可与 signature 对比,标识该请求来源于微信
		 */

		// 1.排序
		String sortString = AuthApi.sort(TOKEN, timestamp, nonce);

		// 2.sha1加密
		String myString = AuthApi.encryt(sortString);

		// 3.字符串校验
		if (myString != null && !myString.equals("") && myString.equals(signature)) {
			logger.info("微信--签名校验通过");
			// 如果校验成功就返回echostr,微信服务器接收到此输出,才会确认校验完成
			logger.info("返回给微信的 echostr 字符串: " + echostr);
			return echostr;
		} else {
			logger.info("微信--签名校验失败");
			return "";
		}
	}
	
	
	/**
	 * 通过POST请求接收响应消息
	 * @param request
	 * @param response
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	@RequestMapping(value="/get", method=RequestMethod.POST)
	@ResponseBody
	public String getMessage(HttpServletRequest request,HttpServletResponse response) throws Exception{
		try {
			Map<String, String> map = MessageApi.xmlToMap(request);
			
			String message = messageService.replyMessage(map);
			
			return message; 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 保存微信公众号账户信息
	 * @param request
	 * @param response
	 * @param name
	 * @param originalId
	 * @param appid
	 * @param appsecret
	 * @param token
	 * @return
	 */
	@RequestMapping("/account/save")
	@ResponseBody
	public Result saveAccount(HttpServletRequest request, HttpServletResponse response, String name, 
			String originalId, String appid, String appsecret, String token){
		
		Result result = wechatAccountService.saveAccount(name,originalId,appid,appsecret,token);
		
		return result;
	}
	
	/**
	 * 保存关注公众号自动回复消息内容
	 * @param request
	 * @param response
	 * @param content
	 * @return
	 */
	@RequestMapping("/reply/subscribe/save")
	@ResponseBody
	public Result saveSubscribeReply(HttpServletRequest request, HttpServletResponse response,String content){
		
		Result result = wechatReplyService.saveSubscribeReply(content);
		
		return result;
	}
	
	/**
	 * 保存关注公众号自动回复消息内容
	 * @param request
	 * @param response
	 * @param content
	 * @return
	 */
	@RequestMapping("/reply/keywords/save")
	@ResponseBody
	public Result saveKeywordsReply(HttpServletRequest request, HttpServletResponse response,String keywords, String content){
		
		Result result = wechatReplyService.saveKeywordsReply(keywords,content);
		
		return result;
	}
	
	/**
	 * 查询关键字
	 * @return
	 */
	@RequestMapping("/reply/keywords/get")
	public Result getKeywordsReply(){
		Result result = wechatReplyService.getKeywordsReply();
		
		return result;
	}
	
	/**
	 * 创建菜单(暂时只做测试用)
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/createMenu")
	@ResponseBody
	public BaseResult createMenu(HttpServletRequest request,HttpServletResponse response){
		String access_token = (String) request.getSession().getAttribute("ACCESS_TOKEN");
		
		if(access_token == null){
			//Token token = TokenApi.getToken(APPID, APPSECRET);
			access_token = TaskList.Wechat_Access_Token;
			HttpSession session = request.getSession();
			session.setAttribute("ACCESS_TOKEN", access_token);
			session.setMaxInactiveInterval(7200);
			System.out.println(access_token);
		}
		
		
		
		// 第一组菜单
		Button button1 = new Button();
		button1.setName("中翰云油");
		
		List<Button> sub_button1 = new ArrayList<>();
		
		Button subButton1 = new Button();
		subButton1.setType("view");
		subButton1.setName("充值卡加油");
		subButton1.setUrl( DOMAIN + "/recharge/oil/card" );
		
		Button subButton2 = new Button();
		subButton2.setName("大客户充油");
		subButton2.setType("view");
		subButton2.setUrl("http://www.zhkjnet.com/zhyy/login");
		
		/*Button subButton3 = new Button();
		subButton3.setName("充油理财");
		subButton3.setType("view");
		subButton3.setUrl("https://www.sina.com");*/
		
		sub_button1.add(subButton1);
		sub_button1.add(subButton2);
		/*sub_button1.add(subButton3);*/
		
		button1.setSub_button(sub_button1 );
		
		// 第二组菜单
		Button button2 = new Button();
		button2.setName("关于平台");
		
		List<Button> sub_button2 = new ArrayList<>();
		Button subButton4 = new Button();
		subButton4.setName("公司简介");
		subButton4.setType("view");
		subButton4.setUrl("http://mp.weixin.qq.com/s/_6WjJBseAr5DuyZJJ4Et6w");
		
		/*Button subButton5 = new Button();
		
		subButton5.setName("最新动态");
		subButton5.setType("view");
		subButton5.setUrl("https://www.sohu.com");*/
		
		sub_button2.add(subButton4);
		//sub_button2.add(subButton5);
		button2.setSub_button(sub_button2 );
		
		// 第三组菜单
		Button button3 = new Button();
		button3.setName("充值教程");
		button3.setType("view");
		button3.setUrl("http://mp.weixin.qq.com/s/GR1FZuxwu2PQx2HTv0DELA");
		
		/*List<Button> sub_button3 = new ArrayList<>();
		Button subButton6 = new Button();
		subButton6.setName("APP下载");
		subButton6.setType("view");
		subButton6.setUrl("https://www.tencent.com");
		sub_button3.add(subButton6 );*/
		
		//button3.setSub_button(sub_button3 );
		
		// 封装菜单
		MenuButtons menuButtons = new MenuButtons();
		Button[] button = new Button[]{button1,button2,button3};
		menuButtons.setButton(button );
		
		String jsonString = JSON.toJSONString(menuButtons);
		
		BaseResult baseResult = MenuApi.createMenu(access_token, jsonString);
		
		return baseResult;
	}
	
	
	
	
}
